<script lang="ts" setup>
import { useAddProduct, useEditProduct, useGetProductAttribute } from '@fl/api/supplier'
import { useMessage } from '@fl/hooks/web/use-message'
import { cloneDeep } from 'lodash-es'

import NormalProps from './comps/normal-props/normal-props.vue'
import SaleProps from './comps/sale-props/sale-props.vue'
import Sku from './comps/sku/sku.vue'

const props = withDefaults(defineProps<{
    productInfo?: any
}>(), {
    productInfo: () => {},
})
const flag = ref<boolean>(true)
const router = useRouter()
const { query } = useRoute()
const detail = defineModel<any>('detail', { required: true })
const { createMessage } = useMessage()
type IskuHeaderData = {
    isFreeInstall: number
    isFreeShip: number
    isIncludeTax: number
}
const skuHeaderData = ref<IskuHeaderData>({
    isFreeInstall: 0,
    isFreeShip: 0,
    isIncludeTax: 0,
})
const productSaleAttributeList = ref<any[]>([])
const dataStructure = ref<any[]>([
    {
        id: '',
        productModel: '',
        skuAttributeInfo: '',
        skuCount: '',
        skuName: '',
        skuPrice: '',
        skuPriceIntroduce: '',
    },
])
const { productInfo } = toRefs(props)

const params = computed(() => ({
    categoryId: productInfo.value.productCategoryId,
}))

const { data: productAttributeList, isLoading: productAttributeLoading } = useGetProductAttribute(params)
const { isPending: isAddProductPending, mutate } = useAddProduct()
const { isPending: isEditProductPending, mutate: EditProductMutate } = useEditProduct()
const isPending = computed(() => productAttributeLoading.value || isAddProductPending.value || isEditProductPending.value)
const normalAttribute = ref()
const saleAttribute = ref()
const attributeObj = ref<any>({})
const newAttributeObj = ref<any>({})
watchEffect(() => {
    if (productAttributeList.value && flag.value) {
        normalAttribute.value = productAttributeList.value.filter((item: any) => item.isSaleAttribute === 0).map((obj) => {
            return {
                attributeId: obj.id,
                attributeName: obj.attributeName,
                attributeValue: obj.attributeValue,
                isCustomerAttribute: obj.isCustomerAttribute,
                isRequired: obj.isRequired,
                isSaleAttribute: obj.isSaleAttribute,
                selectData: '',
            }
        })

        saleAttribute.value = productAttributeList.value.filter((item: any) => item.isSaleAttribute === 1).map(obj => ({ ...obj, attributeValue: obj.attributeValue ? JSON.parse(obj.attributeValue).map(obj => ({ ...obj, flag: false })) : [], flag: false }))
    }
})

watchEffect(() => {
    if (Object.keys(detail.value).length > 0 && flag.value) {
        skuHeaderData.value = {
            isFreeInstall: detail.value.productVO.isFreeInstall,
            isFreeShip: detail.value.productVO.isFreeShip,
            isIncludeTax: detail.value.productVO.isIncludeTax,
        }
        dataStructure.value = JSON.parse(JSON.stringify(detail.value.productSkuVOS))

        for (const item of detail.value.productAttributeVOS) {
            const { attributeCustomer, attributeId, attributeKey, attributeValue, attributeValueId, id, isCustomerAttribute } = item
            const isSaleAttribute = item.isSaleAttribute ? 1 : 0
            const isRequired = item.isRequired ? 1 : 0
            newAttributeObj.value[attributeId || attributeKey] = {
                attributeCustomer,
                attributeId: attributeId || null,
                attributeKey,
                attributeValue,
                attributeValueId,
                id: id || '',
                isCustomerAttribute,
                isRequired,
                isSaleAttribute,
            }
        }
    }
})

watchEffect(() => {
    if (Object.keys(detail.value).length > 0 && detail.value.productAttributeVOS && normalAttribute.value && flag.value) {
        const isCustomerArray = detail.value.productAttributeVOS.filter(item => item.isCustomerAttribute === 1).map((item) => {
            return {
                attributeName: item.attributeKey,
                attributeValue: item.attributeCustomer,
                isCustomerAttribute: item.isCustomerAttribute,
                isRequired: item.isRequired || 0,
                isSaleAttribute: item.isSaleAttribute || 0,
                selectData: '',
            }
        })
        if (flag.value) {
            normalAttribute.value = [...normalAttribute.value, ...isCustomerArray]
        }
        normalAttribute.value.forEach((item: any) => {
            for (let i = 0; i < detail.value.productAttributeVOS.length; i++) {
                const attributeItem = detail.value.productAttributeVOS[i]
                if (item.attributeName === attributeItem.attributeKey) {
                    item.selectData = attributeItem.attributeValue
                    item.attributeValue = attributeItem.attributeCustomer
                    break
                }
            }
        })
    }
})

watchEffect(() => {
    if (Object.keys(detail.value).length > 0 && detail.value.productVO.saleAttributes?.length > 0) {
        productSaleAttributeList.value = [...toRaw(detail.value.productVO.saleAttributes)].map((item) => {
            return {
                attributeKey: item.name,
                attributeValue: item.value,
            }
        })
    }
})

watchEffect(() => {
    if (Object.keys(detail.value).length > 0 && detail.value.productVO.attributeSaleCustomer) {
        saleAttribute.value = JSON.parse(detail.value.productVO.attributeSaleCustomer)
    }
})

function getAttribute(e: any) {
    flag.value = false
    attributeObj.value = toRaw({ ...e })
    Object.keys(attributeObj.value).forEach((key) => {
        newAttributeObj.value[key] = attributeObj.value[key]
    })
}

function isValidJSON(text) {
    try {
        JSON.parse(text)
        return true
    }
    catch (error) {
        return false
    }
}

function goback() {
    router.go(-1)
}

function checkArrays(arr1, arr2) {
    for (let i = 0; i < arr1.length; i++) {
        if (!arr2.includes(arr1[i])) {
            createMessage.warning(`普通属性数据中"${arr1[i]}"属性为必填属性，请先选择`)
            return false
        }
    }
    return true
}

function removeFlagProperty(obj) {
    for (const key in obj) {
        if (typeof obj[key] === 'object' && obj[key] !== null) {
            removeFlagProperty(obj[key]) // 递归处理嵌套对象
        }
        else if (key === 'flag') {
            delete obj[key]
        }
    }
}

function next() {
    console.log(saleAttribute.value, 'saleAttribute')
    // 遍历表格数据中字段不为空
    const newProductInfo = ref(cloneDeep(productInfo.value))
    attributeObj.value = query?.id ? newAttributeObj.value : attributeObj.value
    console.log('attributeObj.value', attributeObj.value)
    saleAttribute.value.forEach((item) => {
        removeFlagProperty(item)
    })
    console.log('saleAttribute.value', saleAttribute.value)
    const data = {
        ...toRaw(skuHeaderData.value),
        ...toRaw(newProductInfo.value),
        attributeSaleCustomer: JSON.stringify(saleAttribute.value),
        productAttributeList: Object.values(attributeObj.value).map((item: any) => {
            const { attributeCustomer, attributeId, attributeKey, attributeValue, attributeValueId, id, isCustomerAttribute, isRequired, isSaleAttribute } = item
            return {
                attributeCustomer: isValidJSON(attributeCustomer) ? attributeCustomer : JSON.stringify(attributeCustomer),
                attributeId,
                attributeKey,
                attributeValue,
                attributeValueId,
                id,
                isCustomerAttribute,
                isRequired,
                isSaleAttribute,
            }
        }),
        productSaleAttributeList: productSaleAttributeList.value,
        productSkuList: [...toRaw(dataStructure.value)].map((item) => {
            const { _X_ROW_KEY, ...rest } = item
            return rest
        }),
    }

    if (normalAttribute.value && normalAttribute.value.length > 0) {
        const attributeNameArr = normalAttribute.value.filter(item => item.isRequired === 1).map(item => item.attributeName)
        const checkAttributeNameArr = data.productAttributeList.map(item => item.attributeKey)
        if (!checkArrays(attributeNameArr, checkAttributeNameArr)) {
            return
        }
    }

    if (!checkDataCompleteness(data.productSkuList)) {
        createMessage.warning('请先完善产品sku数据')
        return
    }

    console.log(data, 'data')
    if (query?.id) {
        EditProductMutate(
            data,
            {
                onSuccess: () => {
                    createMessage.success('编辑成功')
                    router.push('/supplier-pages/product-management/list')
                },
            },
        )
    }
    else {
        mutate(
            data,
            {
                onSuccess: () => {
                    createMessage.success('新增成功')
                    router.push('/supplier-pages/product-management/list')
                },
            },
        )
    }
}
function checkDataCompleteness(productData) {
    for (let i = 0; i < productData.length; i++) {
        const product = productData[i]
        if (!product.skuName || !product.skuCount || !product.productModel || (product.skuPriceType !== 3 && !product.skuPrice)) {
            return false
        }
    }
    return true
}

function getDataStructure(sku: any, arr: any) {
    console.log(sku, arr)
    flag.value = false
    productSaleAttributeList.value = arr
    dataStructure.value = sku
}

function deleteSku() {
    flag.value = false
}
</script>

<template>
    <ElCard shadow="never">
        <ElForm label-position="left"
                :has-footer="false"
        >
            <NormalProps v-model:newAttributeObj="newAttributeObj"
                         v-model:normalAttribute="normalAttribute"
                         @attribute-change="getAttribute($event)"
            />

            <!-- <SaleProps :sale-attribute="saleAttribute"
                       @get-data-structure="getDataStructure"
            /> -->
            <SaleProps v-model:saleAttribute="saleAttribute"
                       @get-data-structure="getDataStructure"
            />

            <Sku v-model:dataStructure="dataStructure"
                 v-model:skuHeaderData="skuHeaderData"
                 @delete-sku="deleteSku"
            />
        </ElForm>

        <template #footer>
            <div class="flex justify-center">
                <el-button type="info"
                           @click="goback"
                >
                    返回
                </el-button>

                <el-button type="primary"
                           :loading="isPending"
                           @click="next"
                >
                    提交
                </el-button>
            </div>
        </template>
    </ElCard>
</template>
